package com.hwl.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hwl.eduservice.mapper.SubjectMapper;
import com.hwl.eduservice.pojo.Subject;
import com.hwl.eduservice.pojo.excel.ExcelSubjectData;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Slf4j
@NoArgsConstructor
@AllArgsConstructor
public class ExcelSubjectDataListener extends AnalysisEventListener<ExcelSubjectData> {

    private SubjectMapper subjectMapper;

    private Map<String, Set<String>> map;

    /**
     * 遍历每一行的记录
     */
    @Override
    public void invoke(ExcelSubjectData data, AnalysisContext analysisContext) {
        String oneTitle = data.getLevelOneTitle();
        String twoTitle = data.getLevelTwoTitle();

        if (StringUtils.isEmpty(oneTitle)) return;

        //添加一级分类
        if (!map.containsKey(oneTitle)) {
            Subject oneSubject = new Subject().setTitle(oneTitle);
            subjectMapper.insert(oneSubject);

            //这里的value不能用null！需要创建一个空的set，否则第54行判断时可能会报空指针异常
            map.put(oneTitle, new HashSet<>());

            if (StringUtils.isEmpty(twoTitle)) return;
            //当一级分类是第一次添加时，那么它其下的二级分类是一定需要添加的
            Subject twoSubject = new Subject().setTitle(twoTitle).setParentId(oneSubject.getId());
            subjectMapper.insert(twoSubject);

            map.get(oneTitle).add(twoTitle);
        } else { //该一级分类存在，判断其二级分类是否需要添加
            //该一级分类下拥有的所有二级分类title
            Set<String> twos = map.get(oneTitle);
            if (!twos.contains(twoTitle)) {
                Subject oneSubject = subjectMapper.selectOne(new QueryWrapper<Subject>().eq("title", oneTitle));
                Subject twoSubject = new Subject().setTitle(twoTitle).setParentId(oneSubject.getId());
                subjectMapper.insert(twoSubject);

                twos.add(twoTitle);
            }
        }
    }

    /**
     * 所有数据读取之后的收尾工作
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("===============全部数据读取完成==============");
    }
}
